package com.qyhl.webtv.module_microvideo.shortvideo.play;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.gyf.immersionbar.ImmersionBar;
import com.orhanobut.hawk.Hawk;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.microvideo.ShortVideoBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.MShareBoard;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.module_microvideo.R;
import com.qyhl.webtv.module_microvideo.R2;
import com.qyhl.webtv.module_microvideo.shortvideo.play.comment.ShortVideoCommentPopupWindow;
import com.qyhl.webtv.module_microvideo.shortvideo.play.pagerlayoutmanager.OnViewPagerListener;
import com.qyhl.webtv.module_microvideo.shortvideo.play.pagerlayoutmanager.ViewPagerLayoutManager;
import com.qyhl.webtv.module_microvideo.shortvideo.play.player.ListVideoView;
import com.qyhl.webtv.module_microvideo.shortvideo.play.player.OnItemChildClickListener;
import com.qyhl.webtv.module_microvideo.shortvideo.play.player.QXVideoAdapter;
import com.qyhl.webtv.module_microvideo.shortvideo.play.player.VideoAdapter;
import com.qyhl.webtv.module_microvideo.shortvideo.play.player.VideoManager;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.umeng.socialize.UMShareAPI;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;
import tv.danmaku.ijk.media.player.IMediaPlayer;

/**
 * 播放界面
 */
@Route(path = ARouterPathConstant.SHORT_VIDEO_PLAY)
public class ShortVideoPlayActivity extends BaseActivity implements OnViewPagerListener, ShortVideoPlayContract.ShortVideoPlayView {
    @BindView(R2.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;

    @Autowired(name = "actId")
    String activityId;

    ViewPagerLayoutManager pagerLayoutManager;
    VideoAdapter videoAdapter;

    List<ShortVideoBean> mDataList;

    @Autowired(name = "position")
    int curPosition;

    private VideoAdapter.VideoViewHolder viewHolder;

    private ShortVideoPlayPresenter mPresenter;

    private String userName;

    private String workId;

    private boolean isFirst = false;

    @Autowired(name = "page")
    int page = 2;

    @Autowired(name = "type")
    int type = 0;

    @Override
    protected int getContentView() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        return R.layout.micro_activity_short_video_play;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {

    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mDataList = (List<ShortVideoBean>) getIntent().getSerializableExtra("bean");
        mPresenter = new ShortVideoPlayPresenter(this);
        initView();
    }

    @Override
    protected void setListener() {
        setListeners();
        if (Hawk.contains("login")) {
            userName = CommonUtils.getInstance().getUserName();
        } else {
            userName = "1";
        }
        workId = mDataList.get(curPosition).getId() + "";
        mPresenter.getDetail(workId, userName);
    }


    private void initView() {
        isFirst = true;
        BusFactory.getBus().register(this);

        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setEnableRefresh(false);
        if (type == 0) {
            refresh.setEnableLoadMore(false);
        } else {
            refresh.setEnableLoadMore(true);
        }

        pagerLayoutManager = new ViewPagerLayoutManager(this, LinearLayoutManager.VERTICAL);
        pagerLayoutManager.setOnViewPagerListener(this);


        recycleView.setLayoutManager(pagerLayoutManager);

        videoAdapter = new VideoAdapter(this, recycleView);

        recycleView.setAdapter(videoAdapter);

        videoAdapter.setData(mDataList);
        recycleView.scrollToPosition(curPosition);


    }

    @SuppressLint("ClickableViewAccessibility")
    private void setListeners() {
        recycleView.setOnTouchListener((view, e) -> {
            final int action = e.getActionMasked();
            switch (action) {
                case MotionEvent.ACTION_DOWN://手指按下
                    break;
                case MotionEvent.ACTION_CANCEL:
                    break;
                case MotionEvent.ACTION_MOVE://手指移动（从手指按下到抬起 move多次执行）
                    break;
                case MotionEvent.ACTION_UP://手指抬起
                    if (recycleView.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING &&
                            pagerLayoutManager.findSnapPosition() == 0) {
                        if (recycleView.getChildAt(0).getY() == 0 &&
                                recycleView.canScrollVertically(1)) {//下滑操作
                            recycleView.stopScroll();
                        }
                    }
                    break;
                default:
                    break;
            }

            return false;
        });

        videoAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onClickListener(View view, Object bean, int position) {
                int i = view.getId();
                ShortVideoBean shortVideoBean = (ShortVideoBean) bean;
                if (i == R.id.comment) {
                    ShortVideoCommentPopupWindow commentPopupWindow = new ShortVideoCommentPopupWindow(ShortVideoPlayActivity.this, workId, mDataList.get(curPosition).getCommentNumber());
                    commentPopupWindow.showPopupWindow();
                } else if (i == R.id.comment_num) {
                    ShortVideoCommentPopupWindow commentPopupWindow2 = new ShortVideoCommentPopupWindow(ShortVideoPlayActivity.this, workId, mDataList.get(curPosition).getCommentNumber());
                    commentPopupWindow2.showPopupWindow();
                } else if (i == R.id.forword_num) {
                    MPermissionUtils.requestPermissionsResult(ShortVideoPlayActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new MPermissionUtils.OnPermissionListener() {
                        @Override
                        public void onPermissionGranted() {
                            MShareBoard shareBoard = new MShareBoard(ShortVideoPlayActivity.this, shortVideoBean.getId() + "", shortVideoBean.getTitle(), shortVideoBean.getLogo(), "", 24, false);
                            shareBoard.showPopupWindow();
                        }

                        @Override
                        public void onPermissionDenied() {
                            MPermissionUtils.showTipsDialog(ShortVideoPlayActivity.this);
                        }
                    });
                } else if (i == R.id.like_num) {
                    CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                        @Override
                        public void login(boolean isLogin) {
                            if (isLogin) {
                                userName = CommonUtils.getInstance().getUserName();
                                mPresenter.doPraise(workId, userName);
                            } else {
                                Toasty.normal(ShortVideoPlayActivity.this, "尚未登录或登录已失效！").show();
                                RouterManager.routerLogin(ShortVideoPlayActivity.this, 0);
                            }
                        }

                        @Override
                        public void error(String s) {

                        }
                    });
                }
            }

            @Override
            public void onClickListener(View view, Object bean, int position, boolean isFollow) {

            }
        });


        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getData(activityId, page + "", type);
            }
        });
    }

    @OnClick({R2.id.close_btn, R2.id.shoot_btn})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.close_btn) {
            finish();
        } else if (i == R.id.shoot_btn) {

            String activityStatus = CommonUtils.getInstance().getShortVideoState();
            switch (activityStatus) {
                case "BEGINNING":
                    MPermissionUtils.requestPermissionsResult(ShortVideoPlayActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO}, new MPermissionUtils.OnPermissionListener() {
                        @Override
                        public void onPermissionGranted() {

                            CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                                @Override
                                public void login(boolean isLogin) {
                                    if (isLogin) {
                                        if (StringUtils.isMi8()) {
                                            Bundle bundle = new Bundle();
                                            bundle.putString("id", activityId);
                                            RouterManager.router(ARouterPathConstant.SHORT_VIDEO_SHOOT2, bundle);
                                        } else {
                                            Bundle bundle = new Bundle();
                                            bundle.putString("id", activityId);
                                            RouterManager.router(ARouterPathConstant.SHORT_VIDEO_SHOOT, bundle);
                                        }
                                    } else {
                                        Toasty.normal(ShortVideoPlayActivity.this, "尚未登录或登录已失效！").show();
                                        RouterManager.routerLogin(ShortVideoPlayActivity.this, 0);
                                    }
                                }

                                @Override
                                public void error(String s) {

                                }
                            });

                        }

                        @Override
                        public void onPermissionDenied() {
                            MPermissionUtils.showTipsDialog(ShortVideoPlayActivity.this);
                        }
                    });
                    break;
                case "END":
                    showToast("活动已结束！", 4);
                    break;
                default:
                    showToast("活动未开始！", 4);
                    break;
            }
        }
    }

    @Override
    public void onInitComplete() {
        playVideo(curPosition);
    }

    @Override
    public void onPageSelected(int position, boolean isBottom) {
        if (viewHolder != null && viewHolder.videoTag != null) {
            viewHolder.videoTag.setVisibility(View.GONE);
        }

        if (isFirst) {
            curPosition = position;
            workId = mDataList.get(position).getId() + "";
            mPresenter.getDetail(workId, userName);
        } else {
            if (position != curPosition) {
                curPosition = position;
                workId = mDataList.get(position).getId() + "";
                mPresenter.getDetail(workId, userName);
            }
        }
    }


    @Override
    public void onPageRelease(boolean isNext, int position) {
        releaseVideo(position);
    }

    private void playVideo(final int position) {
        viewHolder = (VideoAdapter.VideoViewHolder) recycleView.findViewHolderForLayoutPosition(position);
        ShortVideoBean videoBean = videoAdapter.getDataByPosition(position);
        if (viewHolder != null && !viewHolder.videoView.isPlaying()) {
            viewHolder.videoView.setVideoPath(videoBean.getVideoUrl());
            viewHolder.videoView.getMediaPlayer().setOnInfoListener(new IMediaPlayer.OnInfoListener() {
                @Override
                public boolean onInfo(IMediaPlayer iMediaPlayer, int what, int extra) {
                    if (what == IMediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
                        viewHolder.sdvCover.setVisibility(View.INVISIBLE);
                    } else if (what == IMediaPlayer.MEDIA_INFO_VIDEO_ROTATION_CHANGED) {
                        //这里返回了视频旋转的角度，根据角度旋转视频到正确的画面
                        viewHolder.videoView.setRotation(extra);
                    }
                    return false;
                }
            });

            viewHolder.videoView.getMediaPlayer().setOnErrorListener(new IMediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(IMediaPlayer iMediaPlayer, int i, int i1) {
                    showToast("视频出错，加载失败！", 4);
                    return false;
                }
            });

            viewHolder.videoView.setOnVideoProgressUpdateListener(new ListVideoView.OnVideoProgressListener() {
                @Override
                public void onProgress(float progress, long currentTime) {
                    viewHolder.progressBar.setProgress((int) (progress * 100));

                }
            });
            viewHolder.videoView.setLooping(true);
            viewHolder.videoView.prepareAsync();
        }
    }

    private void releaseVideo(int position) {
        VideoManager.releaseAll();
//        VideoAdapter.VideoViewHolder viewHolder = (VideoAdapter.VideoViewHolder) recycleView.findViewHolderForLayoutPosition(position);
//        if (viewHolder != null) {
//            viewHolder.videoView.stopPlayback();
//            viewHolder.sdvCover.setVisibility(View.VISIBLE);
//        }
    }

    @Override
    protected void onPause() {
        super.onPause();
//        if (viewHolder != null) {
//            if (viewHolder.videoTag != null) {
//                viewHolder.videoTag.setVisibility(View.VISIBLE);
//            }
//            viewHolder.videoView.pause();
//        }
        VideoManager.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        if (viewHolder != null) {
//            if (viewHolder.videoTag != null) {
//                viewHolder.videoTag.setVisibility(View.GONE);
//            }
//            viewHolder.videoView.start();
//        }
        VideoManager.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        VideoManager.releaseAll();
        BusFactory.getBus().unregister(this);
    }


    @Override
    public void setDetail(ShortVideoBean bean) {
        isFirst = false;
        List<ShortVideoBean> indexList = new ArrayList<>();
        indexList.clear();
        indexList.addAll(mDataList);
        indexList.set(curPosition, bean);
        mDataList.clear();
        mDataList.addAll(indexList);
        videoAdapter.setData(mDataList);
        playVideo(curPosition);
    }

    @Override
    public void setError(String msg) {
        isFirst = false;
        showToast(msg, 4);
        playVideo(curPosition);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void praiseSuccess() {
        if (viewHolder != null) {
            viewHolder.likeNum.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this, R.drawable.short_video_play_like_on_icon), null, null, null);
            viewHolder.likeNum.setText((mDataList.get(curPosition).getThumbsCount() + 1) + "");
        }
    }

    @Override
    public void praiseError(String msg) {
        showToast(msg, 4);
    }

    @Override
    public void setData(List<ShortVideoBean> beanList) {
        refresh.finishLoadMore();
        page++;
        mDataList.addAll(beanList);
        videoAdapter.setData(mDataList);
    }

    @Override
    public void setDataError(String msg) {
        refresh.finishLoadMore();
        showToast(msg, 4);
    }

    @Override
    public void setFollowNum(String followNum) {
        if (viewHolder != null) {
            viewHolder.ForwordNum.setText(followNum);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(Event.refreshCommentNum event) {
        if (event != null) {
            viewHolder.CommentNum.setText(event.getCommmentNum());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void shareSuccess(Event.shareSuccess event) {
        if (event != null) {
            mPresenter.getFollowNum(mDataList.get(curPosition).getId() + "");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);

    }

}
